package com.icoolkj.mall.order01.config.demo.controller;

import com.icoolkj.mall.common.Result;
import com.icoolkj.mall.order01.config.demo.dto.OrderRequest;
import com.icoolkj.mall.order01.config.demo.dto.OrderResponse;
import com.icoolkj.mall.order01.config.demo.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/01/16 14:41
 */
@RefreshScope
@Slf4j
@RestController
@RequestMapping("/api/order")
public class OrderController implements ApplicationListener<RefreshScopeRefreshedEvent> {

    @Autowired
    private OrderService orderService;

    @GetMapping("/getOrderByUserId")
    public Result<List<OrderResponse>> getOrderByUserId(@RequestParam("userId") Long userId){
        log.info("根据用户ID：{} 查询订单信息", userId);
        try {
           return orderService.getOrderByUserId(userId);
        } catch (RuntimeException e) {
            return Result.fail(e.getMessage());
        }
    }

    @Value("${order.quantity}")
    private int quantity;

    @PostMapping("post1")
    public Result<OrderResponse> post1(@RequestBody OrderRequest orderRequest) {
        OrderResponse  orderResponse  = new OrderResponse();
        // 设置数量
        orderResponse.setOrderQuantity(quantity);
        return  Result.ok(orderResponse);
    }

    // 触发 @RefreshScope 执行逻辑会导致 @Scheduled 定时任务失效
    // 定时任务每隔 3s 执行一次
    @Scheduled(cron = "*/3 * * * * ?")
    public void scheduled() {
        System.out.println("定时任务正常执行...");
    }

    @Override
    public void onApplicationEvent(RefreshScopeRefreshedEvent event) {
        this.scheduled();
    }
}
